import Parser from "web-tree-sitter";
import * as path from "path";
import { Logger } from '../src/logger/Logger';

let setedPath = '';

export function getBaseDir(): string {
    if (setedPath === '') {
        try {
            return __dirname;
        } catch {
            return process.cwd();
        }
    } else {
        return setedPath;
    }
}

/**
 * TreeSitter解析器管理类
 */
class treeSitterParser {
    private static initPromise: Promise<void> | null = null;
    private static parserInstance = new Map<string, Parser>();

    public static async initParser(wasmFileName: string): Promise<Parser> {
        // 确保全局的 Parser.init() 只被调用一次
        if (!this.initPromise) {
            this.initPromise = Parser.init().catch((error: any) => {
                this.initPromise = null;
                Logger.error(`Failed to initialize Tree-sitter parser: ${error}`);
                throw error;
            });
        }

        // 等待全局初始化完成
        await this.initPromise;

        let parser = this.parserInstance.get(wasmFileName);
        if (parser) {
            return parser;
        }

        try {
            const extensionPath = path.join(getBaseDir(), 'tools');
            const pathLang = path.join(extensionPath, wasmFileName);
            const lang = await Parser.Language.load(pathLang);

            parser = new Parser();
            parser.setLanguage(lang);

            this.parserInstance.set(wasmFileName, parser);
            return parser;
        } catch (error) {
            Logger.error(`Failed to load language ${wasmFileName}: ${error}`);
            throw error;
        }
    }
}

// 导出initParser函数以保持向后兼容
export async function initParser(wasmFileName: string): Promise<Parser> {
    return treeSitterParser.initParser(wasmFileName);
}
